package service

import (
	"QHMedLink/model"

	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

// 关联积分订单（需PointsOrder模型存在）
func PointsOrdersByUID(db *gorm.DB, uid string) ([]model.PointsOrder, error) {
	var orders []model.PointsOrder
	if err := db.Where("user_id = ?", uid).Find(&orders).Error; err != nil {
		return nil, err
	}
	return orders, nil
}

// 1. 创建用户（带唯一约束校验）
func CreateUser(db *gorm.DB, phone string) (*model.User, error) {
	user := &model.User{Phone: phone}
	err := db.Transaction(func(tx *gorm.DB) error {
		return tx.Clauses(clause.OnConflict{DoNothing: true}).Create(user).Error
	})
	return user, err
}

// 2. 按手机号查询用户
func GetUserByPhone(db *gorm.DB, phone string) (*model.User, error) {
	var user model.User
	if err := db.Where("phone = ?", phone).First(&user).Error; err != nil {
		return nil, err
	}
	return &user, nil
}

// 3. 更新用户积分（原子操作）
func UpdateRemainingPoints(db *gorm.DB, userID uint, delta int) error {
	return db.Model(&model.User{}).
		Where("user_id = ?", userID).
		Update("remaining_points", gorm.Expr("remaining_points + ?", delta)).Error
}

// 4. 批量查询用户（分页）
func GetUsersByPage(db *gorm.DB, page, size int) ([]model.User, error) {
	var users []model.User
	offset := (page - 1) * size
	if err := db.Offset(offset).Limit(size).Order("registration_time DESC").Find(&users).Error; err != nil {
		return nil, err
	}
	return users, nil
}

// 5. 软删除扩展（需添加DeletedAt字段）
func SoftDeleteUser(db *gorm.DB, userID uint) error {
	return db.Model(&model.User{}).
		Where("user_id = ?", userID).
		Update("is_deleted", true).Error
}
